<template>
    <div class="ces-table-page" :class="{'table-fullscreen':fullScreen}">
        <!-- 表格操作按钮 -->
        <section v-if="isHandle || isColFilter" class="ces-handle">
            <div class="ces-left-right">
                <div class="leftBox">
                    <template v-for="(item,index) in tableHandles" :key="index">
                        <el-button
                            v-if="!(item.hide && item.hide()) && isHandle"
                            :type="item.type"
                            :icon="item.icon"
                            class="ch_button"
                            :plain="item.plain"
                            @click="item.handle()"
                        >
                            {{ item.label }}
                        </el-button>
                    </template>
                    <slot name="menu-left" />
                    <slot v-if="isHandle" name="handleBtn" />
                </div>
                <div v-if="isColFilter" class="rightBox flexJce flexAic">
                    <el-tooltip v-if="actions.refresh.state" effect="light" content="刷新列表" placement="bottom">
                        <el-icon class="icon-set" @click="$emit('refresh')"><Refresh /></el-icon>
                    </el-tooltip>
                    <el-dropdown v-if="actions.layout.state">
                        <el-icon class="icon-set"><Grid /></el-icon>

                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item @click="tableSizeChange('large')">宽松</el-dropdown-item>
                                <el-dropdown-item @click="tableSizeChange('default')">中等</el-dropdown-item>
                                <el-dropdown-item @click="tableSizeChange('small')">小型</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                    <el-popover
                        v-if="actions.filter.state"
                        placement="bottom"
                        width="200"
                        trigger="hover"
                        popper-class="filterTableCol"
                        content=""
                    >
                        <el-card shadow="never">
                            <template #header>
                                <div class="flex mbottom10">
                                    <span style="flex: 1">列名称</span>
                                    <span class="defaultColor cursor fs12" @click="reset">重置</span>
                                </div>
                            </template>

                            <el-checkbox-group v-model="checkList" @change="checkListChange">
                                <div v-for="(item,index) in tableCols" :key="index" class="ele-tool-column-item">
                                    <el-checkbox :label="item.prop">{{ item.label }}</el-checkbox>
                                </div>
                            </el-checkbox-group>
                        </el-card>
                        <template #reference>
                            <el-icon class="icon-set"><Setting /></el-icon>
                        </template>
                    </el-popover>
                    <el-tooltip v-if="actions.fullScreen.state" effect="light" content="全屏切换" placement="bottom">
                        <el-icon class="icon-set" @click="fullScreenChange"><FullScreen /></el-icon>
                    </el-tooltip>
                </div>
            </div>
        </section>
        <div class="ces-table">
            <el-table
                v-if="resetTableVis"
                v-bind="$attrs"
                ref="cesTable"
                v-loading="loading"
                :data="tableData"
                :size="tableSize"
                :border="isBorder"
                class="ces-table-el"
                :default-selections="defaultSelections"
                @selection-change="select"
                @select-all="selectAll"
                @sort-change="sortChange"
            >
                <el-table-column
                    v-if="isSelection" type="selection" align="center"
                    :reserve-selection="reserveSelection"
                    :resizable="false"
                />
                <el-table-column
                    v-if="isIndex" type="index" :label="indexLabel" align="center"
                    :resizable="false"
                    width="50"
                />
                <!-- 数据栏-->
                <template v-for="(item,index) in tableCols" :key="index">
                    <el-table-column
                        v-if="checkList.indexOf(item.prop)>-1 && !item.tableHide"
                        :prop="item.prop"
                        :label="item.label"
                        :height="item.height"
                        :show-overflow-tooltip="item.showOverflowTooltip || false"
                        :fixed="item.fixed"
                        :width="item.width"
                        :align="item.align || 'center'"
                        :sortable="item.sortable || false"
                    >
                        <template #header="scope">
                            <span>{{ item.label }}</span>
                            <slot name="customHeader" :row="scope.row" :prop="item.prop" />
                        </template>
                        <template #default="scope">
                            <div>
                                <!--Render-->
                                <v-slot v-if="item.type === 'Render' && item.render" :render="item.render" :row="scope.row" :index="scope.$index" :column="item" />
                                <!-- html -->
                                <span
                                    v-if="item.type==='Html'" @click="item.handle && item.handle(scope.row)"
                                    v-html="item.html(scope.row)"
                                />
                                <!-- 默认 -->
                                <span
                                    v-if="!item.type"
                                    :style="item.itemStyle && item.itemStyle(scope.row)"
                                    :class="item.itemClass && item.itemClass(scope.row)"
                                    @click="item.handle && item.handle(scope.row)"
                                >{{ (item.formatter && item.formatter(scope.row)) || scope.row[item.prop] }}</span>
                                <div v-if="item.type === 'customCol'">
                                    <slot :name="item.prop" :row="scope.row" :prop="item.prop" />
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                </template>
                <template v-if="actions.edit.state || actions.del.state || actions.actionSlot.state">
                    <el-table-column :width="actionsWidth"  label="操作">
                        <template #default="scope">
                            <div class="actions">
                                <slot name="actions" :row="scope.row" />
                            </div>
                        </template>
                    </el-table-column>
                </template>
            </el-table>
        </div>
        <!-- 分页 -->
        <section v-if="actions.pagination.state" class="ces-pagination">
            <el-pagination
                background
                :pager-count="5"
                :page-sizes="[5,10,20,30,40,50,100]"
                layout="total,sizes ,prev, pager, next,jumper"
                :page-size="pagination.pageSize"
                :current-page="pagination.currentPage"
                :total="pagination.total"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange"
            />
        </section>
    </div>
</template>

<script>
import { Refresh,Grid,Setting,FullScreen } from '@element-plus/icons-vue'
import vSlot from './vSlot.vue'// 自定义内容的组件



export default {
    name: 'NTable',
    components: {
        vSlot,
        Refresh,
        Grid,
        FullScreen,
        Setting
    },
    props: {
        // 表格型号：mini,medium,small
        isBorder: { type: Boolean, default: true },
        loading: { type: Boolean, default: false },
        // 表格操作
        isHandle: { type: Boolean, default: false },
        tableHandles: { type: Array, default: () => [] },
        // 表格数据
        tableData: { type: Array, default: () => [] },
        // 表格列配置
        tableCols: { type: Array, default: () => [] },
        // 是否显示表格复选框
        isSelection: { type: Boolean, default: false },
        defaultSelections: { type: [Array, Object], default: () => null },
        // 是否显示表格索引
        isIndex: { type: Boolean, default: false },
        indexLabel: { type: String, default: '序号' },
        // 是否显示分页
        isPagination: { type: Boolean, default: false },
        // 分页数据
        pagination: { type: Object, default: () => ({ pageSize: 10, currentPage: 1, total: 0 }) },
        // 是否需要列筛选
        isColFilter: { type: Boolean, default: true },
        // 勾选有分页是否保存状态
        reserveSelection: { type: Boolean, default: false },
        // 表格是否自适应
        autoHeight: { type: Boolean, default: true },
        // 控制操作组件的展示
        actions: { type: Object, default: () => {} },
        disableHeight:{
            //取消自适应高度
            type: Boolean, default: false
        }
    },
    data() {
        return {
            checkList: [], // 列名称展示项
            tableSize: 'default', // 表格size
            fullScreen: false, // 表格是否全屏,
            resetTableVis: true,// 重置的时候 对表格显隐,
            actionsWidth:310
        }
    },
    watch: {
        'defaultSelections'(val) {
            this.$nextTick(function() {
                if (Array.isArray(val)) {
                    val.forEach(row => {
                        this.$refs.cesTable.toggleRowSelection(row, true)
                    })
                } else {
                    this.$refs.cesTable.toggleRowSelection(val, true)
                }
            })
        },
        checkList(val){
            if(val.length>0){
                this.actionsColumnWidth()
            }
        }
    },
    created() {
        this.tableSize = this.size
        this.init()
        this.checkTableCols()
    },
    mounted() {
        //把cesTable的方法提到当前组件，不打包正常的，打包后this指向不到所有的方法了，坑死我了，弄了2天
        // const entries = Object.entries(this.$refs.cesTable)
        // for (const [key, value] of entries) {
        //     this[key] = value
        // }
    },
    methods: {
        /**
         *  获取操作按钮数量改变操作栏宽度
         * @param {int} time
         */
        actionsColumnWidth(time = 200){
            if(this.checkList.length<1 && !parent) return;
            setTimeout(() => {
                let parent = document.getElementsByClassName('actions')[0]
                if(parent.childNodes.length>0){
                    let width = 20
                    for (let index = 0; index <parent.children.length; index++) {
                        const element = parent.children[index];
                        width += element.clientWidth + 11;
                    }
                    if(width >= 200){
                        this.actionsWidth = width
                    }
                    if(width < this.actionsWidth){
                        this.actionsWidth = width
                    }
                    console.log(width,this.actionsWidth )
                }
            },time);
        },

        // 检查表头数据列的唯一key是否有重复或者是否存在唯一key
        checkTableCols() {
            let flag = false
            let name = ''
            for (let i = 0; i < this.tableCols.length; i++) {
                if (!this.tableCols[i].prop) {
                    flag = true
                    name = this.tableCols[i].label
                    break
                }
            }
            if (flag) {
                this.$message.error(`表格列【${name}】的prop字段不存在，请添加！`)
                return false
            }
            let arr = []
            this.tableCols.forEach(item => {
                arr.push(item.prop)
            })
            let nary = arr.sort()
            for (let i = 0; i < arr.length; i++) {
                if (nary[i] === nary[i + 1]) {
                    this.$message.error(`表格列prop字段存在重复【${nary[i]}】，请检查！`)
                }
            }

        },
        init() {
            let checkList = []
            this.tableCols.forEach(item => {
                checkList.push(item.prop)
            })
            this.checkList = checkList
        },
        reset() {
            let checkList = []
            this.tableCols.forEach(item => {
                checkList.push(item.prop)
            })
            this.checkList = checkList
            this.resetTableVis = false
            setTimeout(() => {
                this.resetTableVis = true
            })
        },
        // 表格勾选
        select(rows, row) {
            this.$emit('select', rows, row)
        },
        // 全选
        selectAll(rows) {
            this.$emit('select', rows)
        },
        // 换页
        handleCurrentChange(val) {
            this.pagination.currentPage = val
            this.$emit('refresh')
        },
        // 每页条数变化
        handleSizeChange(val) {
            this.pagination.pageSize = val
            this.$emit('refresh')
        },
        // 表格排序
        sortChange(column) {
            this.$emit('refreshSort', column)
        },
        // 表格密度配置
        tableSizeChange(size) {
            this.tableSize = size
        },
        fullScreenChange() {
            this.fullScreen = !this.fullScreen
        },
        checkListChange() {
            this.resetTableVis = false
            setTimeout(() => {
                this.resetTableVis = true
            })
        }
    }
}
</script>

<style lang="scss" scoped>
    .ces-table-page {
        flex: 1;
        display: flex;
        flex-direction: column;
        &.table-fullscreen {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            box-sizing: border-box;
            margin-top: 0;
            background-color: #ffffff;
            z-index: 1011;
            padding: 20px;
            overflow-y: auto;
        }
        .ces-handle {
            .ces-left-right {
                padding:8px 10px;
                display: flex;
                border-top: 1px solid #EBEEF5;
                border-left: 1px solid #EBEEF5;
                border-right: 1px solid #EBEEF5;
            }
            .leftBox {
                display: flex;
                flex: 1;
                .el-button + .el-button {
                    margin-left: 0;
                }
                .el-button {
                    margin-right: 10px;
                }
            }
            .rightBox {
                width: 160px;
                text-align: right;
                .icon-set {
                    border-radius: 2px;
                    border: 1px solid #e5e5e5;
                    box-sizing: border-box;
                    font-size: 16px;
                    margin-left: 10px;
                    height: 25px;
                    width: 25px;
                    line-height: 25px;
                    cursor: pointer;
                    color: #999;
                }
            }
        }
        :deep(.ces-table) {
            .el-table{
                height: 100%;
                background-color: #f9f9fb;
                .el-table__body-wrapper {
                    overflow-y: auto;
                }
                .el-checkbox{
                    height: auto;
                }
            }
            .el-table__cell{
                background-color: #f9f9fb;
                color: #000;
            }
            @import './scss/tableCommon.scss';
        }
        .ces-pagination {
            text-align: right;
            padding-top: 15px;
            background-color: #ffffff;
            position: relative;
            .el-pagination {
                padding: 0;
            }
        }
    }
</style>
